// 导入数据(表格)
define([
  "publicTool/ajax",
  "uploader",
  "publicBusiness/verifyPermission",
  "publicBusiness/layerPc",
  "artlib",
  "text!template/dataImport/import-error.html!strip",
  "mCustomScrollbar",
  "style!webuploader",
  "style!mCustomScrollbarCss",
], function(ajax, WebUploader, Permission, layerPc, template, errorTpl, mCustomScrollbar) {
  // 模板变量-错误提示行号
  template.defaults.imports.importErrorIdx = 0;

  var UpLoadExcel = function(opt){
  	this.config(opt);
  	this.init();
    // this.bindUploadEvent();
  	this.uploadExcelFile();
  }

  // 基础项配置
  UpLoadExcel.prototype.config = function(opt){
  	var defaults = {
  		ele: "dataImport",//按钮对象
  		disableClass: "disable",//禁用class用于阻止事件的标识
  		btn_class: "btn_import kong style_1",//按钮自定义类名
  		apiName: "api_business",//请求的接口项目名称
  		url: "",//请求的数据地址
  		permission: "",//导入权限标识
      callUploadSuccess: "",//导入成功的回调
      // webuploader 参数配置
  		uploadData: {
  			auto: false, // 选完文件后，是否自动上传
  			swf: 'js/Uploader.swf', // swf文件路径
  			fileVal: "file_info",
  			method: "POST",
  			sendAsBinary: false,
  			pick: {
  			  // id: '#dataImport', // id
  			  multiple: false // false  单选 
  			},
  			accept: {
  			  title: 'Excel文件',
  			  extensions: 'xls,xlsx',
  			  mimeTypes: 'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  			}
  		},//webuploader配置参数
      paramsData: {
        "merchant_id": localStorage.merchant_id,
        "platform_id": localStorage.platform_id,
        "file_info": "",
      }//ajax请求参数
  	}
  	this.config = $.extend(true, defaults, opt);
  	// 拼装正确参数
  	this.config.uploadData.pick.id = "#" + this.config.ele;
  	
  	this.ele = $("#" + this.config.ele);
  	this.layerIdx = null;//加载层的动画索引
  	this.uploader = WebUploader.create(this.config.uploadData);
  	// 拼装参数
    // =添加自定义类名
  	$(this.config.uploadData.pick.id).find(".webuploader-pick").addClass(this.config.btn_class);
    // =添加权限
    if(this.config.permission){
      this.config.paramsData.identification = this.config.permission;
    }
  }

  // 初始化
  UpLoadExcel.prototype.init = function(){
  	
  }

  // 绑定上传事件
  UpLoadExcel.prototype.bindUploadEvent = function(){
  	var _this = this;
  	this.ele.click(function(){
  		// 禁用按钮
  		if( $(this).hasClass(_this.config.disableClass) ){
  			return;
  		}
  		// 验证数据权限
  		if(_this.config.permission){
  			if( !Permission.verifyPermission(_this.config.permission) ){
  				return;
  			}
  		}
  		// 执行上传事件
  		// _this.uploadExcelFile();
  	})
  }

  // 上传文件
  UpLoadExcel.prototype.uploadExcelFile = function(){
  	var _this = this;
  	this.uploader.on('fileQueued', function(file) {
  	  var files = _this.uploader.getFiles();
      var formData = new FormData();
      if(_this.config.paramsData.merchant_id){
        formData.append('params[data][merchant_id]', localStorage.merchant_id);
      }
      if(_this.config.paramsData.platform_id){
        formData.append('params[data][platform_id]', localStorage.platform_id);
      }
      formData.append('params[data][identification]', _this.config.permission);

      formData.append('api_name', _this.config.apiName);
      formData.append('uri', _this.config.url);

      formData.append('params[keys][token_key]', localStorage.member_id);
      formData.append('params[keys][token_val]', localStorage.token);

  	  for (var i = 0; i < files.length; i++) {
        _this.config.paramsData.file_info = files[i].source.source;
        formData.append('file_info', files[i].source.source);
  	  }
      // 请求动画
      _this.exportAnimation();
  	  // 发送请求
  	  $.ajax({
        contentType: false,
        processData: false,
        dataType: "json",
        type: "POST",
        url: "/agent/index.php?func=api",
        data: formData
  	  }).done(function(data) {
        if (data.status == false) {
          let msg = data.code_user_msg || data.code_msg;
          layer.close( _this.layerIdx );
          if(data.result && data.result.length){
            layerPc.alert({
              title: "错误提示",
              skin: "layer-ext-jwb ctrl_btn_no_border",
              area: ["550px", "400px"],
              content: template.render( $(errorTpl).html(), data),
              end: function(){
                _this.uploader.removeFile(file);
              }
            });
            $(".wrong_list_table").mCustomScrollbar();
          }else{
            layerPc.success({
               title: '提示',
               tip_ok_con: msg,
               tip_type: 2,
               time: 5000,
               call: function(){
                  _this.uploader.removeFile(file);
               }
            });
          }
        } else {
          layer.close( _this.layerIdx );
          layerPc.msg({
            contents: "导入成功！",
            call: function(){
              _this.uploader.removeFile(file);
              _this.config.callUploadSuccess && _this.config.callUploadSuccess();
            }
          });
        }
      });
    });
  }

  // 导入加载动画
  // 参数一 iTplType [动画类型 目前只有默认的如果不能满足可以自行添加]
  UpLoadExcel.prototype.exportAnimation = function(iTplType){
  	var sTpl = ""; //模板字符串值

  	switch(iTplType){
  		case 1:
  			sTpl = "123";
  			break;
  		default:
  			sTpl = '<div class="loading_zone">' +
  						'<div class="loading_img"></div>' +
  						'<p>数据正在导入，请您耐心等待</p>' +
  					'</div>';
  	};

  	this.layerIdx = layer.open({
  		title: "",
  		shadeClose: false,
  		closeBtn: 0,
  		btn: [],
  		content: sTpl,
  		skin: "loading_style",
  		area: ["386px", "256px"]
  	});
  }
  
  return UpLoadExcel;
});